package com.gzhuxj201.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gzhuxj201.entity.Class;
import com.gzhuxj201.entity.PageBean;
import com.gzhuxj201.entity.Student;
import com.gzhuxj201.entity.StudentDto;
import com.gzhuxj201.mapper.ClassMapper;
import com.gzhuxj201.mapper.StudentMapper;
import com.gzhuxj201.service.StudentService;
import com.gzhuxj201.util.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassMapper classMapper;


    @Transactional
    @Override
    public PageBean page(Integer page, Integer pageSize,String sno,String username,Short gender) {
        Integer startIdx=(page-1)*pageSize;

       List<Student> studentList= studentMapper.page(startIdx,pageSize,sno,username,gender);

        List<StudentDto> studentDtoList = studentList.stream().map((item) -> {
            StudentDto studentDto=new StudentDto();
            BeanUtils.copyProperties(item,studentDto);
            //获取班级名称并添加到studentDto中
            Class aClass = classMapper.selectById(item.getClassId());
            studentDto.setClassName(aClass.getName());
            return studentDto;
        }).collect(Collectors.toList());


        PageBean pageBean = new PageBean(studentDtoList.size(),studentDtoList);

        return pageBean;
    }

    @Override
    public int add(Student student) {
        return studentMapper.add(student);
    }

    @Transactional
    @Override
    public StudentDto selectById(String sno) {
        Student student = studentMapper.selectById(sno);
        StudentDto studentDto=new StudentDto();
        BeanUtils.copyProperties(student,studentDto);
        //获取班级名称并添加到studentDto中
        Class aClass = classMapper.selectById(student.getClassId());
        studentDto.setClassName(aClass.getName());
        return studentDto;
    }

    @Override
    public int update(Student student) {
        return studentMapper.update(student);
    }

    @Override
    public int deleteByIds(List<Integer> ids) {
        return studentMapper.deleteBySnoes(ids);
    }

    @Override
    public Student login(String username, String password) {
        return studentMapper.selectByUsernameAndPassword(username,password);
    }

    @Override
    public Student selectByUsername(String username) {
        return studentMapper.selectByUsername(username);
    }
    @Override
    public List<Student> selectUnsubmitStu(Integer id, String courseId) {
        return studentMapper.selectUnsubmitStu(id,courseId);
    }
}
